<?php
class Application_Model_Categories extends Application_Model_Db_Db
{
    /**
     * get all child categories
     * @param int $parentId
     * @param boold $isDeptCategories
     * @return array
     */
    public function getCategoriesByParentId($parentId=0, $isDeptCategories=false) {
        $where = '';
        //if we build main menu - take into consederation
        //category visible(in menu) settings
        if (!$isDeptCategories) {
            $where = ' AND `category`.`menu` = 1';
        }
        $sql = "SELECT
                    `category`.`id`,
                    `category`.`parent_id`,
                    `category`.`category_name`,
                    `category`.`alias`,
                    `type`.`type`
                FROM `category`
                INNER JOIN `category_type` AS `type`
                    ON `category`.`type_id` = `type`.`id`
                WHERE
                    1
                    AND `category`.`parent_id` = ?
                    {$where}
                ORDER BY `position`";
        return $this->_db->fetchAll($sql, $parentId);
    }

    /**
     * get category id by category alias
     * @param $alias
     * @return string
     */
    public function getCategoryIdByAliasAndDepartmentId($alias, $departmentId=0) {
        $sql = "SELECT
                    `category`.`id`
                FROM `category`
                WHERE 
                    1
                    AND `category`.`alias` = ?
                    AND `category`.`department_id` = ?";
        return $this->_db->fetchOne($sql, array($alias, $departmentId));
    }    

    public function getDepartmentIdByCategoryAlias($alias) {
        $sql = "SELECT
                    `category`.`department_id`
                FROM `category`
                WHERE 
                    1
                    AND `category`.`alias` = ?
                    AND `category`.`department_id` != 0";
        return $this->_db->fetchOne($sql, $alias);
    }

    /**
     * Get first department category, 
     * except main department category.
     * It need for determine start page     
     * @param int $departmentId
     * @return array
     */
    public function getFirstDepartmentCategory($departmentId) {
        $sql = "SELECT
                    `category`.`id`,
                    `category`.`alias`,
                    `type`.`type`
                FROM `category`
                INNER JOIN `category_type` AS `type`
                    ON `category`.`type_id` = `type`.`id`
                WHERE 
                    1                     
                    AND `category`.`department_id` = ?
                    AND `type`.`type` != 'department'
                    AND `type`.`type` != 'title'
                ORDER BY `category`.`position`";
        return $this->_db->fetchRow($sql, $departmentId);
    }
}